package model

import (
	"bookProjectSrv/global"
	"gorm.io/gorm"
)

// 用户
type User struct {
	gorm.Model
	Username string
	Password string
	Mobile   string
	Email    string
	Sex      int
	Salt     string
}

func NewUser() *User {
	return &User{}
}

func (m *User) GetMobile(mobile string) (u *User, err error) {
	err = global.DB.Where("mobile = ?", mobile).First(&u).Error
	return
}

func (m *User) Regester(u *User) (*User, error) {
	err := global.DB.Create(&u).Error
	return u, err
}

func (m *User) Update(u *User) (*User, error) {
	err := global.DB.Table("users").Where("id=?", u.ID).Updates(u).Error
	return u, err
}

func (m *User) Get(id int) (u *User, err error) {
	err = global.DB.Where("id = ?", id).First(&u).Error
	return
}

func (m *User) GetUsers(offset, limit int) ([]User, int64, error) {
	var users []User
	var total int64
	err := global.DB.Offset(offset).Limit(limit).Find(&users).Error
	if err != nil {
		return nil, 0, err
	}
	err = global.DB.Table("users").Count(&total).Error
	if err != nil {
		return nil, 0, err
	}
	return users, total, nil
}

// 根据username获取单个数据
func (m *User) GetByUsername(username string) (u *User, err error) {
	err = global.DB.Where("username = ?", username).First(&u).Error
	return
}

func (m *User) Delete(id int64) (err error) {
	err = global.DB.Table("users").Where("id = ?", id).Delete(&m).Error
	return
}
